package edu.whu.webgis.utils;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;


public class ImgUtil {
    private ImgUtil(){}
    private static final String Base ;

    static {
        Base = new File("").getAbsolutePath()+ "/src/main/resources/img/";
    }

    public static synchronized String save(String img){
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date())  + ".jpg" ;
        String replace = img.replace("data:image/jpeg;base64,", "");
        String fullName = Base + fileName;
        decrypt(replace,fullName);
        return fileName;
    }
    public static byte[] get(String name){
        File file = new File(Base + name);
        InputStream is = null;
        try {
            is = Files.newInputStream(file.toPath());
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            byte[] bb = new byte[1024];
            int ch;
            ch = is.read(bb);
            while (ch != -1) {
                byteStream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            return byteStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getBase64Jpg(String name){
        return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(ImgUtil.get(name));
    }

    private static void decrypt(String base64, String filePath) {
        if (base64 == null && filePath == null || (base64 != null && base64.length() == 0) ) {
            return;
        }
        try {
            Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64), StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
